package com.hnev.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;


	public class JDBC extends JFrame{
	// 定义组件
	private JScrollPane scpDemo;
	private JTableHeader jth;
	private JTable tabDemo;
	private JButton btnShow,btnAdd,btnDelete;
	// 构造方法
	public JDBC(){
	// 窗体的相关属性的定义
	super("水果信息展示");
	this.setSize(600,600);
	this.setLayout(null);
	this.setLocation(400,80);
	// 创建组件
	this.scpDemo = new JScrollPane();
	this.scpDemo.setBounds(100,50,400,270);
	this.btnShow = new JButton("显示水果信息");
	this.btnShow.setBounds(150,360,300,30);
	this.btnAdd=new JButton("增加");
	this.btnAdd.setBounds(150,430,100,50);
	this.btnDelete=new JButton("删除");
	this.btnDelete.setBounds(350,430,100,50);
	// 给按钮注册监听
	this.btnShow.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent ae){
	btnShow_ActionPerformed(ae);
	}
	});
	// 将组件加入到窗体中
	add(this.scpDemo);
	add(this.btnShow);
	add(this.btnAdd);
	add(this.btnDelete);
	
	// 显示窗体
	this.setVisible(true);
	}
	// 点击按钮时的事件处理
	public void btnShow_ActionPerformed(ActionEvent ae){
	// 以下是连接数据源和显示数据的具体处理方法，请注意下
	try{
	// 获得连接
	Class.forName("com.mysql.jdbc.Driver");
	String url = "jdbc:mysql://localhost:3306/fruitSystem";
	String user ="root";
	String password="998520";
	Connection conn= DriverManager.getConnection(url,user,password);
	// 建立查询条件
	String sql = "select * from fruit"; 
	PreparedStatement pstm = conn.prepareStatement(sql);
	// 执行查询
	ResultSet rs = pstm.executeQuery();
	// 计算有多少条记录
	int count = 0;
	while(rs.next()){
	count++;
	}
	rs = pstm.executeQuery();
	// 将查询获得的记录数据，转换成适合生成JTable的数据形式
	Object[][] info = new Object[count][4];
	count = 0;
	while(rs.next()){
	info[count][0] = Integer.valueOf( rs.getInt("编号"));
	info[count][1] = rs.getString("姓名");
	info[count][2] = Double.valueOf( rs.getDouble("价格") );
	info[count][3] =  Double.valueOf( rs.getDouble("数量") );
	count++;
	}
	// 定义表头
	String[] title = {"编号","名字","价格","数量"};
	// 创建JTable
	this.tabDemo = new JTable(info,title);
	// 显示表头
	this.jth = this.tabDemo.getTableHeader();
	// 将JTable加入到带滚动条的面板中
	this.scpDemo.getViewport().add(tabDemo); 
	}catch(ClassNotFoundException cnfe){
	JOptionPane.showMessageDialog(null,"数据源错误","错误",JOptionPane.ERROR_MESSAGE);
	}catch(SQLException sqle){
	JOptionPane.showMessageDialog(null,"数据操作错误","错误",JOptionPane.ERROR_MESSAGE);
	}
	
	
	}
	public static void main(String[] args){
	new JDBC();
	}
	}
